package com.example.seckill.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.hutool.core.util.StrUtil;
import com.example.seckill.annotation.CurrentUser;
import com.example.seckill.common.CommonResult;
import com.example.seckill.mapper.PermissionMapper;
import com.example.seckill.mapper.RoleMapper;
import com.example.seckill.pojo.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
   RoleMapper roleMapper;

    @Resource
    PermissionMapper permissionMapper;

    @PostMapping
    public CommonResult<?> save(@RequestBody Role Role) {
        System.out.println("插入角色");
        roleMapper.insert(Role);
        return CommonResult.success(Role);
    }

    @PutMapping
    public CommonResult<?> update(@RequestBody Role Role) {
        roleMapper.updateById(Role);
        return CommonResult.success(Role);
    }

    // 改变权限接口
    @PutMapping("/changePermission")
    public CommonResult<?> changePermission(@CurrentUser User user, @RequestBody Role role) {
        // 先根据角色id删除所有的角色跟权限的绑定关系
        permissionMapper.deletePermissionsByRoleId(role.getId());
        // 再新增 新的绑定关系
        for (Integer permissionId : role.getPermissions()) {
            permissionMapper.insertRoleAndPermission(role.getId(), permissionId);
        }

        // 判断当前登录的用户角色是否包含了当前操作行的角色id，如果包含，则返回true，需要重新登录。
        List<UserRole> userRoles = roleMapper.getUserRoleByUserId(Math.toIntExact(user.getId()));
        if (userRoles.stream().anyMatch(userRole -> userRole.getRoleId().equals(role.getId()))) {
            return CommonResult.success(true);
        }
//        如果不包含，则返回false，不需要重新登录。
        return CommonResult.success(false);
    }

    @DeleteMapping("/{id}")
    public CommonResult<?> update(@PathVariable Long id) {
        roleMapper.deleteById(id);
        return CommonResult.success(id);
    }

    @GetMapping("/{id}")
    public CommonResult<?> getById(@PathVariable Long id) {
        return CommonResult.success(roleMapper.selectById(id));
    }

    @GetMapping("/all")
    public CommonResult<?> all() {
        return CommonResult.success(roleMapper.selectList(null));
    }

    @GetMapping
    public CommonResult<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<Role> wrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Role::getName, search);
        }
        Page<Role> RolePage = roleMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        List<Role> records = RolePage.getRecords();
        // 给角色设置绑定的权限id数组
        for (Role record : records) {
            System.out.println(1);
            Integer roleId = record.getId();
            System.out.println("rid="+roleId);
            System.out.println(permissionMapper.getRolePermissionByRoleId(roleId).isEmpty());
            List<Integer> permissions = permissionMapper.getRolePermissionByRoleId(roleId).stream().filter(u->u!=null).map(RolePermission::getPermissionId).collect(Collectors.toList());

            record.setPermissions(permissions);
        }
        return CommonResult.success(RolePage);
    }
}
